#include "spacecol2d.h"
#define BPR 10
SpaceCol2D::SpaceCol2D()
{
    m_blocks = NULL;
    numBlock = 0;
    m_tree = NULL;
    m_widget = NULL;
}


SpaceCol2D::~SpaceCol2D()
{
     if (m_tree) m_tree->freeTree(m_tree->treeRoot);
     delete m_blocks;

}

void SpaceCol2D::updateTree(TreeGen2D *newTree)
{
    if (m_tree) m_tree->freeTree(m_tree->treeRoot);
    m_tree = newTree;
}

// generate markers
void SpaceCol2D::generateMarkers()
{
    //GLUquadric * mQuadric = gluNewQuadric();

    numBlock = BPR*BPR;
    m_blocks = new Block[numBlock];
    double size = m_widget->width()/BPR;
    for (int i = 0; i < numBlock; i++)
    {
        Block * currentBlock = &m_blocks[i];
        currentBlock->col = (int) i % BPR;
        currentBlock->row = (int) i / BPR;
        currentBlock->updateSize(size, float3 (currentBlock->col * size, currentBlock->row * size));
        for (int j = 0; j < currentBlock->numMarkers; j++)
        {
            double random = ((double) rand()) / (double) RAND_MAX;
            double range = (currentBlock->col + 1) * size - currentBlock->startCoord.x;
            currentBlock->m_markers[j*5 + 0] = (random*range) + currentBlock->startCoord.x; // x coord
            random = ((double) rand()) / (double) RAND_MAX;
            range = (currentBlock->row + 1) * size - currentBlock->startCoord.y;
            currentBlock->m_markers[j*5 + 1] = (random*range) + currentBlock->startCoord.y; // y coord
            currentBlock->m_markers[j*5 + 2] = 0; // z coord, will be used in 3D;
            currentBlock->m_markers[j*5 + 3] = -1; // does not belong to any bud;
            currentBlock->m_markers[j*4 + 4] = -1; // no distance calculated yet;
           /* glColor3f(1.0, 1.0, 0);
            glPushMatrix();
            glTranslatef(currentBlock->m_markers[j*5 + 0], currentBlock->m_markers[j*5 + 1], 0.0);
            gluDisk(mQuadric, 0, 2.0/2.0, 10, 10);
            glPopMatrix();*/
        }
    }
    drawMarkers();
    //cout <<" Done generating markers" << endl;
}

// draw markers, for debugging purpose.
void SpaceCol2D::drawMarkers()
{
    GLUquadric * mQuadric = gluNewQuadric();

     double size = m_widget->width()/BPR;
    for (int i = 0; i < numBlock; i++)
    {
        Block * currentBlock = &m_blocks[i];



        for (int j = 0; j < currentBlock->numMarkers; j++)
        {
            glColor3f(0, 0.0, 1.0);
            glPushMatrix();
            glTranslatef(currentBlock->m_markers[j*5 + 0], currentBlock->m_markers[j*5 + 1], 0.0);
            gluDisk(mQuadric, 0, 2.0/2.0, 10, 10);
            glPopMatrix();

        }
    }
}

// create a tree root
void SpaceCol2D::initialize(float3 start, float3 end, float theta, float diameter)
{
    m_tree = new TreeGen2D();
    m_tree->treeRoot->start = start;
    m_tree->treeRoot->end = end;
    m_tree->treeRoot->theta = theta;
    m_tree->treeRoot->diameter = diameter;
    internodeLength = diameter;
}
